package com.topi.integration.interceptor.payload;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;

import com.topi.integration.transformer.helper.MessageSourceConverterHelper;

@Component
public class PayloadClientInterceptor implements ClientInterceptor {

	private static final Logger logger = Logger
			.getLogger(PayloadClientInterceptor.class);

	private MessageSourceConverterHelper messageSourceConverterHelper;


	public PayloadClientInterceptor() {
		messageSourceConverterHelper = new MessageSourceConverterHelper();
	}

	@Override
	public boolean handleRequest(MessageContext messageContext)	throws WebServiceClientException {
		logger.info("..............................Sending Request");
		Source source = messageContext.getRequest().getPayloadSource();
		log(source);
		return true;
	}

	protected void log(Source source) {
		try {
			logger.info(messageSourceConverterHelper.convertToString(source));
		} catch (TransformerException e) {
			logger.error(e);
		}
	}

	@Override
	public boolean handleResponse(MessageContext messageContext)
			throws WebServiceClientException {
		logger.info("..............................Receiving Response");
		log(messageContext.getResponse().getPayloadSource());
		return true;
	}

	@Override
	public boolean handleFault(MessageContext messageContext)
			throws WebServiceClientException {
		logger.info("..............................Receiving Fault");
		log(messageContext.getResponse().getPayloadSource());
		return true;
	}

	@Override
	public void afterCompletion(MessageContext arg0, Exception arg1)
			throws WebServiceClientException {
		
	}



}
